package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.article.IScheduleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dto.Task;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.OcrUtil;
import com.heima.utils.ProtostuffUtil;
import com.heima.utils.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.AutoScanService;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lzy
 * @date 2022/7/17 14:18
 */
@Service
@Slf4j
public class AutoScanServiceImpl implements AutoScanService {
    @Autowired
    private WmNewsService wmNewsService;
    @Autowired
    private MinIoTemplate minIoTemplate;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private IArticleClient articleClient;

    @Override
    public void autoScanWmNews(Long newsId) throws Exception {
        //入参判空
        if (newsId == null) {
            log.warn("newsId为空");
            return;
        }
        //1.查询新闻信息
        //新闻为空，响应失败
        WmNews wmNews = wmNewsService.getById(newsId);
        if (wmNews == null) {
            log.warn("新闻" + newsId + "为空");
            return;
        }
        //2.提取新闻文字
        String title = wmNews.getTitle();
        String content = wmNews.getContent();
        String text = getText(title, content);
        //3.提取新闻图片
        String images = wmNews.getImages();
        List<byte[]> imageList = getImage(images, content);

        //通过OCR提取图片中的文字
        String textFromOrc = orcCheck(imageList);
        text = text + "_" + textFromOrc;

        //0 使用DFA算法进行自建敏感词处理
        Boolean dfaCheck = dfaCheck(text);
        if (!dfaCheck){
            //DFA检测不通过的话，需更新文章状态
            updateWmNews(2,"DFA审核没通过",null,newsId.intValue());
            return;
        }

        //4.调用文字审核接口
        //审核失败 -> wmNews修改方法
        //审核不确定 -> wmNews修改方法
        Map textScan = greenTextScan.greeTextScan(text);
        Boolean textScanResult = checkResult(textScan, null, newsId.intValue());
        if (!textScanResult){
            log.warn("文字审核失败");
            return;
        }
        //5.调用图片审核接口
        //审核失败 -> wmNews修改方法
        //审核不确定 -> wmNews修改方法
        Map imageScan = greenImageScan.imageScan(imageList);
        Boolean imageScanResult = checkResult(textScan, null, newsId.intValue());
        if (!imageScanResult){
            log.warn("图片审核失败");
            return;
        }
        //6.远程调用ArticleClient保存文章
        //判断响应结果是不是200
        ArticleDto dto = wmNews2ArticleDto(wmNews);
        ResponseResult responseResult = articleClient.saveArticle(dto);
        if (responseResult == null || responseResult.getCode() != 200){
            log.warn("文章保存失败");
            return;
        }
        Long articleId = (Long) responseResult.getData();
        //7.将articleid写回到wmNews表中
        updateWmNews(9,"审核通过",articleId,newsId.intValue());
    }

    @Autowired
    private WmChannelService wmChannelService;
    @Autowired
    private WmUserService wmUserService;
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    private String orcCheck(List<byte[]> images) throws TesseractException, IOException {
        if (CollectionUtils.isEmpty(images)){
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (byte[] image : images) {
            //调用orc工具类，提取里面的文字内容
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(image);
            BufferedImage read = ImageIO.read(byteArrayInputStream);

            String text = OcrUtil.doOcr(read);
            //将文字内容组合成一个字符串，最终返回
            builder.append("_").append(text);
        }
        return builder.toString();
    }

    private Boolean dfaCheck(String text){
        if (StringUtils.isEmpty(text)){
            return true;
        }
        //0.1 调用敏感词mapper，查询所有敏感词
        QueryWrapper<WmSensitive> wrapper = new QueryWrapper<>();
        wrapper.select("sensitives");
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(wrapper);
        //遇到集合就判空
        if (CollectionUtils.isEmpty(wmSensitives)){
            return true;
        }
        //.filter(Objects::nonNull)过滤查出的为空的字段
        //.map(WmSensitive::getSensitives）  提取WmSensitive中sensitive字段
        //.collect(Collectors.toList())  用这个方法将字段创建成一个新的集合
        List<String> words = wmSensitives.stream().filter(Objects::nonNull).map(WmSensitive::getSensitives).collect(Collectors.toList());
        //0.2 DFA初始化
        SensitiveWordUtil.initMap(words);
        //0.3 DFA敏感词匹配
        Map<String, Integer> result = SensitiveWordUtil.matchWords(text);
        //0.4 判断结果
        return CollectionUtils.isEmpty(result);
    }

    public ArticleDto wmNews2ArticleDto(WmNews wmNews){
        if (wmNews == null){
            return null;
        }
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,dto);
        dto.setLayout(wmNews.getType());
        //获取渠道名
        Integer channelId = wmNews.getChannelId();
        if (channelId != null){
            WmChannel channel = wmChannelService.getById(channelId);
           if (channel != null){
               dto.setChannelName(channel.getName());
           }
        }
        //获取作者名
        Integer userId = wmNews.getUserId();
        if (userId != null){
            dto.setAuthorId(userId.longValue());
            WmUser wmUser = wmUserService.getById(userId);
            if (wmUser != null){
                dto.setAuthorName(wmUser.getName());
            }
        }
        return dto;
    }

    private Boolean updateWmNews(Integer status, String reason, Long articleId, Integer newsId) {
        WmNews wmNews = new WmNews();
        wmNews.setStatus(status.shortValue());
        wmNews.setReason(reason);
        wmNews.setArticleId(articleId);
        wmNews.setId(newsId);
        if (articleId != null){
            wmNews.setArticleId(articleId);
        }
        return wmNewsService.updateById(wmNews);
    }

    private Boolean checkResult(Map result, Long articleId, Integer newsId) {
        if (CollectionUtils.isEmpty(result)) {
            log.warn("审核结果为空");
            return false;
        }
        String suggestion = (String) result.get("suggestion");
        if ("pass".equals(suggestion)) {
            return true;
        } else if ("block".equals(suggestion)) {
            //更新wmNews状态
            updateWmNews(2, "未通过", articleId, newsId);
            return false;
        }else if ("review".equals(suggestion)) {
            //更新wmNews状态
            updateWmNews(3, "转为人工审核", articleId, newsId);
            return false;
        }
        return true;
    }

    private List<byte[]> getImage(String images, String content) {
        //先定义一个总的集合来装两组图片
        List<String> allImageList = new ArrayList<>();
        //对入参images进行判空
        if (StringUtils.isNotEmpty(images)) {//入参不为空进行下一步获取
            //提取images里面的图片链接
            String[] split = images.split(",");
            List<String> list = Arrays.asList(split);
            allImageList.addAll(list);
        }
        //提取content里面的图片
        List<Map> maps = JSON.parseArray(content, Map.class);
        if (!CollectionUtils.isEmpty(maps)) {
            List<String> contentImageList = new ArrayList<>();
            for (Map map : maps) {
                if (CollectionUtils.isEmpty(map)) {
                    continue;
                }
                Object type = map.get("type");
                if ("image".equals(type)) {
                    String value = (String) map.get("value");
                    contentImageList.add(value);
                }
            }
            allImageList.addAll(contentImageList);
        }
        //将两组图片地址合在一起
        List<byte[]> result = new ArrayList<>();
        for (String img : allImageList) {
            if (StringUtils.isEmpty(img)) {
                continue;
            }
            //用minio的download将string转为byte[]
            byte[] bytes = minIoTemplate.downLoadFile(img);
            result.add(bytes);
        }
        //将byte[]集合返回
        return result;
    }

    private String getText(String title, String content) {
        if (StringUtils.isBlank(content)) {
            return title;
        }
        //1.提取content里面的文字内容
        List<Map> maps = JSON.parseArray(content, Map.class);
        if (CollectionUtils.isEmpty(maps)) {
            return title;
        }
        StringBuilder builder = new StringBuilder();
        for (Map item : maps) {
            if (CollectionUtils.isEmpty(item)) {
                continue;
            }
            Object type = item.get("type");
            if ("text".equals(type)) {
                String value = (String) item.get("value");
                builder.append(value);
            }
        }
        //2.将content文字内容和title进行组合
        builder.append("_").append(title);
        //3.返回组合结果
        return builder.toString();
    }

    @Autowired
    private IScheduleClient scheduleClient;

    @Scheduled(fixedRate = 1000)
    public void getTask(){
        ResponseResult responseResult = scheduleClient.poll();
        if (responseResult == null || responseResult.getCode() != 200){
            log.warn("消费失败");
            return;
        }
        String data = (String) responseResult.getData();
        if (StringUtils.isEmpty(data)){
            log.warn("没有任务可消费");
            return;
        }
        Task task = JSON.parseObject(data,Task.class);
        if (task == null){
            log.warn("没有任务可消费");
            return;
        }
        byte[] parameters = task.getParameters();
        WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
        if (wmNews == null){
            log.warn("参数缺失");
            return;
        }
        try {
            autoScanWmNews(wmNews.getId().longValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
